﻿using SmartCity.ProcessEngine.Infrastructure.Interfaces;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SmartCity.ProcessEngine.Infrastructure.Implements
{
    public class BaseRepository<T>:IBaseRepository<T> where T : class
    {
        private readonly DataDbContext context;

        /// <summary>
        /// 数据库上下文
        /// </summary>
        public DataDbContext DB
        {
            get { return context; }
        }

        public BaseRepository(DataDbContext context)
        {
            this.context = context;//context.Database.BeginTransaction()  开启事务的标志
        }

        public async Task<int> AddAsync(T t)
        {
            await context.Set<T>().AddAsync(t);
            return await context.SaveChangesAsync();
        }
        /// <summary>
        /// 批量添加
        /// </summary>
        /// <param name="list">实体集合</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> AddRangeAsync(List<T> list)
        {
            await context.Set<T>().AddRangeAsync(list);
            return await context.SaveChangesAsync();
        }

        //public Task<int> DeleteAsync(int id)
        //{
            
        //}

        //public Task<int> DeleteRangeAsync(List<T> list)
        //{
        //    throw new NotImplementedException();
        //}

        public IQueryable<T> GetAll()
        {
            return context.Set<T>().AsQueryable();
        }

        public async Task<T> FindAsync(int id)
        {
            return await context.Set<T>().FindAsync(id);
        }

        public async Task<int> UpdateAsync(T t)
        {
            context.Set<T>().Update(t);
            return await context.SaveChangesAsync();
        }
        /// <summary>
        /// 批量更新
        /// </summary>
        /// <param name="list">实体集合</param>
        /// <returns>返回受影响行数</returns>
        public async Task<int> UpdateRangeAsync(List<T> list)
        {
            context.Set<T>().UpdateRange(list);
            return await context.SaveChangesAsync();
        }
    }
}
